#include "LuaOperate.h"
#include <string.h>

LuaOperate* LuaOperate::I_operate = NULL;
lua_State* LuaOperate::L_luaState = NULL;

LuaOperate::LuaOperate()
{
	L_luaState = lua_open();
	luaopen_base(L_luaState);
	luaopen_string(L_luaState);
	luaopen_math(L_luaState);
}

LuaOperate::~LuaOperate()
{
	lua_close(L_luaState);
}

LuaOperate* LuaOperate::GetInstance(char* filename)
{
	if(I_operate == NULL)
	{
		I_operate = new LuaOperate();
	}
	//if (NULL != L)
	//{
	//	lua_close(L);
	//}
	//L = NULL;
	//delete I;
	//I = NULL;
	//I = new LuaOperate();

	//luaL_loadfile(L,filename);
	//lua_pcall(L,0,0,0);

	if(filename != NULL)
	{
		luaL_loadfile(L_luaState,filename);
		lua_pcall(L_luaState,0,0,0);
	}
	//else
	//{
	//	luaL_loadfile(L_luaState,"level1.lua");
	//	lua_pcall(L_luaState,0,0,0);
	//}
	return I_operate;
}

bool LuaOperate::GetValueByName(char* pName,char* pOut)
{
	lua_getglobal(L_luaState,pName);
	if(!lua_isstring(L_luaState,-1))
	{
		return false;
	}
	else
	{
		strcpy(pOut,lua_tostring(L_luaState,-1));
	}
	return true;
}

bool LuaOperate::ReloadFile(char*  filename)
{
	//if(filename == NULL)
	//{
	//	if(luaL_loadfile(L_luaState,"level1.lua") != 0)
	//	{
	//		return false;
	//	}
	//}
	//else
	{

		lua_close(L_luaState);
		L_luaState = NULL;
		L_luaState = lua_open();
		luaopen_base(L_luaState);
		luaopen_string(L_luaState);
		luaopen_math(L_luaState);
		luaL_loadfile(L_luaState,filename);
		lua_resume(L_luaState, 0);
		
		//if(luaL_loadfile(L_luaState,filename) != 0)
		//{
		//	return false;
		//}
	}

	lua_pcall(L_luaState,0,0,0);
	return true;
}

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
int LuaOperate::getGlobal(lua_State *l,char * varname)
{
	static int count = 0;
	lua_getglobal(l, varname);
	return ++count;
}


float LuaOperate::getGlobalNumber(lua_State *l ,char * varname)
{
	return (float)lua_tonumber    (l, getGlobal(l, varname));
} 


float LuaOperate::getField (const char *key) 
{
	float result = 0.0f;
	lua_pushstring(L_luaState, key);
	lua_gettable(L_luaState, -2);
	result = (float)lua_tonumber(L_luaState, -1);
	lua_pop(L_luaState, 1);
	return result;
}


float LuaOperate::getNumber (const lua_Number num) 
{
	float result = 0.0f;
	lua_pushnumber(L_luaState, num);
	lua_gettable(L_luaState, -2);
	result = (float)lua_tonumber(L_luaState, -1);
	lua_pop(L_luaState, 1);
	return result;
}


void LuaOperate::GetTableNum(char * tablename)
{
	lua_getglobal(L_luaState, tablename);
}